package book.demo;

import org.junit.Test;

import java.text.MessageFormat;
import java.util.concurrent.CountDownLatch;

/**
 * 指令重排序测试
 */
public class CommandReorderTest {

    int a,b,x,y;

    @Test
    public void test() throws InterruptedException {

        while (true) {
            a = b = x = y = 0;
            CountDownLatch countDownLatch = new CountDownLatch(2);
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    a = 1;
                    x = b;
                    countDownLatch.countDown();
                }
            };

            Thread t2 = new Thread() {
                @Override
                public void run() {
                    b = 2;
                    y = a;
                    countDownLatch.countDown();
                }
            };

            t1.start();
            t2.start();

            countDownLatch.await();
            //因为指令重排序，可能输出:x=0,y=0
            System.out.println(MessageFormat.format("x={0},y={1}", x, y));
        }
    }
}
